//
//  SDSkinAnalysisVC.m
//  skinDetection
//
//  Created by  liangzhun on 2018/11/2.
//  Copyright © 2018年  liangzhun. All rights reserved.
//

#import "SDSkinAnalysisVC.h"
#import "SDCompareDetcetionCell.h"
#import "SDDetectionFooter.h"
#import "SDDetectionDataModel.h"
#import "SDSkinAnalysisCell.h"

#import "SDSkinAnalysisCell3.h"

#import "SDProductRecommendVC.h"
#import "SDDetectionReportVC.h"

#import "SDAlertController.h"

#import "SDDiagnoseSkinData.h"
#import "SDQuestionnaireViewController.h"
static NSString *const cellIden = @"SDCompareDetcetionCell";
static NSString *const cellIden2 = @"SDSkinAnalysisCell";

static NSString *const cellIden4 = @"SDSkinAnalysisCell3";

@interface SDSkinAnalysisVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,assign) NSInteger type;//当前显示的数据的皮肤类型

@property (nonatomic ,strong) NSArray *titlesArray;//上半部的button的标题

@property (nonatomic ,strong) SDDetectionFooter *footerView;

@property (nonatomic ,strong) SDDiagnoseSkinData *skinData;//上半部对应的皮肤细分类的数据

@property (nonatomic ,copy) NSString *mySkinImage;//当前皮肤类型对应的拍照

@end

@implementation SDSkinAnalysisVC

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    };
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    _navHeight.constant = SDNavBar_Height;
    
    [self loadData];
   
    self.completeBtn.hidden = YES;
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 50, 0)];
    [self.tableView registerNib:[UINib nibWithNibName:cellIden bundle:nil] forCellReuseIdentifier:cellIden];
    
     [self.tableView registerNib:[UINib nibWithNibName:cellIden2 bundle:nil] forCellReuseIdentifier:cellIden2];
    
      [self.tableView registerNib:[UINib nibWithNibName:cellIden4 bundle:nil] forCellReuseIdentifier:cellIden4];

    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-(30 + SDBottom_Height));
        make.height.mas_equalTo(65);
    }];
    
}

- (void)loadData
{
    self.type = 1;
    SDDetectionDataModel *data = [SDDetectionDataModel shareInstance];
    self.skinData = [data.detectionReportDic objectForKey:[NSString stringWithFormat:@"%lu",(unsigned long)data.type]];
    self.mySkinImage = [data.detectionImageDic objectForKey:[NSString stringWithFormat:@"%lu",(unsigned long)data.type]];
     self.titlesArray = @[@"您的皮肤",self.skinData.subName];
    
    [self.tableView reloadData];
    
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
     NSString *content = indexPath.section == 2? self.skinData.analysis:self.skinData.proposal;
    
    if (indexPath.section == 0) {
        
        SDCompareDetcetionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIden];
        self.type == 1? [cell.skinImage setImage:[UIImage imageNamed:self.mySkinImage]]:[cell.skinImage sd_setImageWithURL:[NSURL URLWithString:self.skinData.img]];
        [cell.skinBtnArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *sBtn = obj;
            sBtn.hidden =  idx < self.titlesArray.count? NO: idx != 3;
            
            if (idx < self.titlesArray.count) {
                
                [sBtn setTitle:self.titlesArray[idx] forState:UIControlStateNormal];
                [sBtn setBackgroundColor:[self getBgColorOfSelectBtnWithSelect:self.type == sBtn.tag]];
               
            }
            
            [sBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
                if (idx < self.titlesArray.count) {
                    self.type = sBtn.tag;
                    [self.tableView reloadData];
                }else{
                    [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
                }
            }];
            
        }];
        
        return cell;
        
    }else if (indexPath.section == 1){
        
        
        SDSkinAnalysisCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIden2];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = 5;
        style.paragraphSpacingBefore = 15;
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:self.skinData.diagnosis];
        [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, att.length)];
        cell.contentLab.attributedText = att;
        
        [cell.skinTypeImageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIImageView *showSkinType = obj;
            showSkinType.hidden = ([SDDetectionDataModel shareInstance].type - 1 != idx);
        }];
        
        return cell;
        
    }else{
      
        SDSkinAnalysisCell3 *cell = [tableView dequeueReusableCellWithIdentifier:cellIden4];
       
        NSString *seperate = @"     ";
        
        content = [content stringByReplacingOccurrencesOfString:@"：" withString:seperate];
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = 5;
        style.paragraphSpacing = 5;
       
         if([content containsString:@"• "])
         {
             [style setFirstLineHeadIndent:-10];
             [style setHeadIndent:10];
         }
       
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:content];
        
        [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, content.length)];
         UIColor *contentColor = indexPath.section == 2? SDMainTextColor:SDMainColor;
         [att addAttribute:NSForegroundColorAttributeName value:contentColor range:NSMakeRange(0, att.length)];
        if (indexPath.section == 2&&[content componentsSeparatedByString:seperate].count > 2) {

            NSString *firstTitle = [content componentsSeparatedByString:seperate].firstObject;
            
            [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(0, firstTitle.length)];
            NSString *second = [content componentsSeparatedByString:seperate][1];
            [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(second.length + seperate.length, firstTitle.length)];
            
        }
        
        [cell.contentLab setAttributedText:att];
        return cell;
        
    }
    
    
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.section == 0? 230 * SDWidth375Scale: indexPath.section == 1?[self getSection1TextHeight]:[self getReasonTextHeightWithIndexPath:indexPath];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0? 11:section == 2? 40:section == 3? 70:0.001;;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return section == 3? [SDDetectionDataModel shareInstance].detectionReportDic.count == 5? 285:0.01:0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CGFloat Height = section == 2? 0:section == 3? 30:0;
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SDMainScreenWidth, 40 + Height)];
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(15, Height, SDMainScreenWidth - 30, 18)];
    NSString *title = section == 2?@"分析":section == 3?@"建议":@"";
    [titleLab setText:title];
    [titleLab setTextColor:SDMainTextColor];
    [titleLab setFont:Font(18)];
    [header addSubview:titleLab];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(15, 23 + Height, 36, 2)];
    [line setBackgroundColor:SDMainTextColor];
    line.layer.cornerRadius = 1.f;
    line.layer.masksToBounds = YES;
    [header addSubview:line];
    
    return section < 2? nil:header;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SDMainScreenWidth, 145)];
    UIButton *recommendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [recommendBtn setFrame:CGRectMake(33, 50, SDMainScreenWidth - 66, 45)];
    [recommendBtn.titleLabel setFont:Font(17)];
    [recommendBtn setBackgroundColor:SDMainColor];
    recommendBtn.layer.cornerRadius = 5.f;
    recommendBtn.layer.masksToBounds = YES;
    [recommendBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
        
        SDProductRecommendVC *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDProductRecommendVC class])];
//        SDDetectionDataModel *data = [SDDetectionDataModel shareInstance];
//        SDDiagnoseSkinData *skinData = [data.detectionReportDic objectForKey:[NSString stringWithFormat:@"%lu",(unsigned long)data.type]];
        //vc.type = skinData.id;
        vc.typeStr = [self getTypesStr];
        [self.navigationController pushViewController:vc animated:YES];
        
    }];
    
    [recommendBtn setTitle:@"产品推荐" forState:UIControlStateNormal];
    [footerView addSubview:recommendBtn];
    
        UIButton *reportBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [reportBtn setFrame:CGRectMake(33, 125, SDMainScreenWidth - 66, 45)];
        [reportBtn.titleLabel setFont:Font(17)];
       
        reportBtn.layer.cornerRadius = 5.f;
        reportBtn.layer.masksToBounds = YES;
        reportBtn.layer.borderWidth = 1.f;
        reportBtn.layer.borderColor = RGBA(255, 120, 155, 1).CGColor;
        [reportBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
            
            if ([SDDetectionDataModel shareInstance].userModel.skinType == 0) {
                [self goQuestionnaireVC];
            }else{
                reportBtn.userInteractionEnabled = NO;
                [self createReportWithBlock:^(BOOL userEnable) {
                    reportBtn.userInteractionEnabled = YES;
                }];
            }
            
        }];
    
        [reportBtn setTitleColor:RGBA(255, 120, 155, 1) forState:UIControlStateNormal];
        [reportBtn setTitle:@"生成报告" forState:UIControlStateNormal];
        [footerView addSubview:reportBtn];
   
//    当所有的皮肤类型的数据都存在，那么就显示商品推荐和生成报告按钮，否则就不显示
    return section < 3? nil:[SDDetectionDataModel shareInstance].detectionReportDic.count == 5?footerView:nil;
    
}
- (NSString *)getTypesStr
{
    NSString *str = @"";
    SDDetectionDataModel *model = [SDDetectionDataModel shareInstance];
    
    for (int t = 0; t < model.detectionReportDic.count; t++) {
        SDDiagnoseSkinData *data = model.detectionReportDic[[NSString stringWithFormat:@"%d",t+1]];
        str = t==0? [NSString stringWithFormat:@"%.f",data.id]:[NSString stringWithFormat:@"%@,%.f",str,data.id];
    }
    return str;
}
- (UIColor *)getBgColorOfSelectBtnWithSelect:(BOOL)sel
{
    return sel == YES? RGBA(250, 207, 92, 1):RGBA(77, 72, 74, 0.3);
}
-(SDDetectionFooter *)footerView
{
    if (!_footerView) {
        
        _footerView = [SDMethodTool getViewWithViewName:NSStringFromClass([SDDetectionFooter class])];
        [_footerView setTypeBtn];
        for (int b = 0; b < _footerView.skinBtnArray.count; b++) {
            
            UIImageView *imageSelect = _footerView.selectImageArray[b];
            imageSelect.hidden = ![[SDDetectionDataModel shareInstance].isDetectionArray[b] boolValue];
            UIButton *typeBtn = _footerView.skinBtnArray[b];
            [typeBtn addTarget:self action:@selector(selectType:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        _footerView.selectBtn = _footerView.skinBtnArray[[SDDetectionDataModel shareInstance].type - 1];
        [self.view addSubview:_footerView];
        
    }
    
    return _footerView;
    
}
- (void)selectType:(UIButton *)sender
{
    NSNumber *selectNum = [SDDetectionDataModel shareInstance].isDetectionArray[sender.tag - 1];
    
    [SDDetectionDataModel shareInstance].type = sender.tag;
    
    if (selectNum.boolValue == NO) {
        
        [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
        
    }else{
        
        [self loadData];
       _footerView.selectBtn = _footerView.skinBtnArray[[SDDetectionDataModel shareInstance].type - 1];
        
    }
    
}
- (IBAction)back:(UIButton *)sender {
    
    SDAlertController *alert = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDAlertController class])];
    
    [alert.view setFrame:self.view.bounds];
    [self.view addSubview:alert.view];
    [self addChildViewController:alert];
    [alert setAlertContent:analysisAlertContent Title:analysisAlertTitle CancelTitle:analysisAlertCancel ConfirmTitle:analysisAlertConfirm];
    [alert.confirmBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
    
}

- (IBAction)goLookDetectionReportDetail:(UIButton *)sender {

    
    
}
//生成报告
- (void)createReportWithBlock:(void(^)(BOOL userEnable))block
{
    [SDNetwork postGenerateReportFinish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
       // LogString([SDNetwork dicToJSONWith:dic]);
        
        block(YES);
        if (!error) {
            SDDetectionReportVC *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDDetectionReportVC class])];
            vc.reportId = [dic[@"data"] intValue];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
    
}
//跳转问卷调查
- (void)goQuestionnaireVC
{
    SDQuestionnaireViewController *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDQuestionnaireViewController class])];
    vc.isFromDetection = YES;
    [self.navigationController pushViewController:vc animated:YES];
   
}
//计算Section1区的文本的高度
- (CGFloat)getSection1TextHeight
{
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    style.paragraphSpacingBefore = 15;
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:self.skinData.diagnosis];
    [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, att.length)];
    CGFloat height = [SDMethodTool getAttTextHeightWithText:att withTextFontSize:Font(15) Width:SDMainScreenWidth - 216] + 15;
    return height > 270? height:270;
    
}
//计算Reason的文本的高度
- (CGFloat)getReasonTextHeightWithIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *content = indexPath.section == 2? self.skinData.analysis:self.skinData.proposal;
    NSString *seperate = @"     ";
    
    content = [content stringByReplacingOccurrencesOfString:@"：" withString:seperate];

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    style.paragraphSpacing = 5;
    //style.paragraphSpacingBefore = 5;
    if([content containsString:@"• "])
    {
        [style setFirstLineHeadIndent:-10];
        [style setHeadIndent:10];
    }
    
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:content];
    
    [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, content.length)];
    UIColor *contentColor = indexPath.section == 2? SDMainTextColor:SDMainColor;
    [att addAttribute:NSForegroundColorAttributeName value:contentColor range:NSMakeRange(0, att.length)];
    if (indexPath.section == 2&&[content componentsSeparatedByString:seperate].count > 2) {
        
        NSString *firstTitle = [content componentsSeparatedByString:seperate].firstObject;
        
        [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(0, firstTitle.length)];
        NSString *second = [content componentsSeparatedByString:seperate][1];
        [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(second.length + seperate.length, firstTitle.length)];
        
        //style.paragraphSpacing = 5;
//        [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, firstTitle.length)];
//
//        [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(second.length + seperate.length, firstTitle.length)];
        
    }
    
    return [SDMethodTool getAttTextHeightWithText:att withTextFontSize:Font(15) Width:SDMainScreenWidth - 30];
    
}
@end
